/**
 * Created by zengyw on 2014/8/11.
 */
define(['../module','services/accounts_service'],
    function (controllers) {
        "use strict";
        controllers.controller('accountListCtrl', ['$scope', 'toaster','$compile','accountsFactory', function ($scope, toaster,$compile,accountsFactory) {
            $scope.dtOptions = {
                "bProcessing": true,
                sAjaxSource: 'http://10.188.192.105:8888',
                sAjaxDataProp: '',
                "sDom": "rt",
                sPaginationType: "full_numbers",
                "aoColumns": [
                    { "mData": "accountName"},
                    { "mData": "totalAssets"},
                    { "mData": "principal"},
                    { "mData": "totalProfit"},
                    { "mData": "totalProfitPercent"},
                    { "mData": "accountType" },
                    { "mData": "accountId"}
                ],
                "fnServerData": function (sUrl, aoData, fnCallback, oSettings) {
                    oSettings.jqXHR = $.ajax({
                        "url": sUrl,
                        beforeSend: function (xhr) {
                            xhr.withCredentials = true;
                        },
                        "data": aoData,
                        "type": 'get',
                        "success": fnCallback,
                        "cache": false
                    });
                },
                "fnInitComplete": function () {
                    //自适应
                    this.fnAdjustColumnSizing(true);
                    //获取datatable
                    var table = $('#accountTable').dataTable();
                    //数据变为重置状态
                    function restoreRow(oTable, nRow) {
                        var aData = oTable.fnGetData(nRow);
                        var jqTds = $('>td', nRow);

                        jqTds[0].innerHTML = "<a ui-sref='site.accountInfo({accountId:"+aData['accountId']+",accountType:\""+aData['accountType']+"\"})'>"+aData['accountName']+"</a>";
                        jqTds[5].innerHTML = aData['accountType'];
                        jqTds[6].innerHTML = "<span class='edit glyphicon glyphicon-edit'></span><span class='cancel glyphicon glyphicon-trash' style='margin-left: 10px;'></span>";
                        $compile(nRow)($scope);
//                        oTable.fnDraw();
                    }
                    //数据变为编辑状态
                    function editRow(oTable, nRow,newRow) {
                        var aData = oTable.fnGetData(nRow);
                        var jqTds = $('>td', nRow);
                        jqTds[0].innerHTML = '<input type="text" class="form-control" value="' + aData['accountName'] + '">';
                        newRow&&(jqTds[5].innerHTML = "<select class='form-control' style='width:100%'><option "+(aData['accountType']=='stock'?'selected':'')+">stock</option><option "+(aData['accountType']=='fund'?'selected':'')+">fund</option></select>");
                        jqTds[6].innerHTML = "<span class='edit glyphicon glyphicon-ok'></span><span class='cancel glyphicon glyphicon-remove' style='margin-left: 10px;'></span>";
                    }
                    //数据变为保存状态
                    function saveRow(oTable, nRow) {
                        var aData = oTable.fnGetData(nRow);
                        //remote save
                        var jqInputs = $('input', nRow);
                        var jqSelect = $('select', nRow);
                        oTable.fnUpdate("<a ui-sref='site.accountInfo({accountId:"+aData['accountId']+",accountType:\""+(jqSelect.length>0?jqSelect[0].value:aData['accountType'])+"\"})'>"+jqInputs[0].value+"</a>", nRow, 0, false);
                        oTable.fnUpdate("￥"+aData['totalAssets'], nRow, 1, false);
                        oTable.fnUpdate("￥"+aData['principal'], nRow, 2, false);
                        oTable.fnUpdate("￥"+aData['totalProfit'], nRow, 3, false);
                        oTable.fnUpdate("￥"+aData['totalProfitPercent'], nRow, 4, false);
                        jqSelect.length>0&&oTable.fnUpdate(jqSelect[0].value, nRow, 5, false);
                        oTable.fnUpdate("<span class='edit glyphicon glyphicon-edit'></span><span class='delete glyphicon glyphicon-trash' style='margin-left: 10px;'></span>", nRow, 6, false);
                        $compile(nRow)($scope);
//                        oTable.fnDraw();
                    }

                    var nEditing = null;//正在编辑的eow数据
                    var nNew = false;//是否正在新建row，true表示正在新建

                    //添加账套
                    $('#addNewAccount').click(function (e) {
                        e.preventDefault();

                        if (nNew && nEditing) {
                            if (confirm("Previose row not saved. Do you want to save it ?")) {
                                saveRow(table, nEditing); // save
//                                $(nEditing).find("td:first").html("Untitled");
                                nEditing = null;
                                nNew = false;

                            } else {
                                table.fnDeleteRow(nEditing); // cancel
                                nEditing = null;
                                nNew = false;

                            }
                        }

                        //获取最新的ID号accountId
                        var aiNew = table.fnAddData({
                            accountId:9999,
                            accountName:'example',
                            totalAssets:'0',
                            principal:'0',
                            totalProfit:'0',
                            totalProfitPercent:'0',
                            accountType:'fund'
                        });
                        var nRow = table.fnGetNodes(aiNew[0]);
                        editRow(table, nRow,true);
                        nEditing = nRow;
                        nNew = true;
                    });

                    //删除账套
                    table.on('click', '.delete', function (e) {
                        e.preventDefault();
                        if (confirm("Are you sure to delete this row ?") == false) {
                            return;
                        }
                        var nRow = $(this).parents('tr')[0];
                        //remote delete
                        table.fnDeleteRow(nRow);
                        alert("Deleted! Do not forget to do some ajax to sync with backend :)");
                    });

                    //取消编辑OR取消新建
                    table.on('click', '.cancel', function (e) {
                        e.preventDefault();

                        if (nNew) {
                            table.fnDeleteRow(nEditing);
                        } else {
                            restoreRow(table, nEditing);
                        }
                        nNew = false;
                        nEditing = null;
                    });

                    //新增OR保存更改
                    table.on('click', '.edit', function (e) {
                        e.preventDefault();

                        /* Get the row as a parent of the link that was clicked on */
                        var nRow = $(this).parents('tr')[0];

                        if (nEditing !== null && nEditing != nRow) {
                            if(nNew){
                                if (confirm("Previose row not saved. Do you want to save it ?")) {
                                    saveRow(table, nEditing); // save
                                    nEditing = null;
                                    nNew = false;

                                } else {
                                    table.fnDeleteRow(nEditing); // cancel
                                    nEditing = null;
                                    nNew = false;

                                    return;
                                }
                            }else{
                                restoreRow(table, nEditing);
                            }
                            editRow(table, nRow);
                            nEditing = nRow;
                        } else if (nEditing == nRow) {
                            /* Editing this row and want to save it */
                            saveRow(table, nEditing);
                            nEditing = null;
                            nNew = false;
                            alert("Updated! Do not forget to do some ajax to sync with backend :)");
                        } else {
                            /* No edit in progress - let's start one */
                            editRow(table, nRow);
                            nEditing = nRow;
                        }
                    });
                },
                "fnCreatedRow": function (nRow, aData, iDataIndex) {
                    $('td:eq(0)', nRow).html("<a ui-sref='site.accountInfo({accountId:"+aData['accountId']+",accountType:\""+aData['accountType']+"\"})'>"+aData['accountName']+"</a>");
                    //总收益率添加百分比符号
                    $('td:eq(1)', nRow).html("￥"+aData['totalAssets']);
                    $('td:eq(2)', nRow).html("￥"+aData['principal']);
                    $('td:eq(3)', nRow).html("￥"+aData['totalProfit']);
                    $('td:eq(4)', nRow).html(aData['totalProfitPercent']+"%");
                    //添加了操作中的编辑和删除按钮
                    $('td:last-child', nRow).html("<span class='edit glyphicon glyphicon-edit'></span><span class='delete glyphicon glyphicon-trash' style='margin-left: 10px;'></span>");
                    $compile(nRow)($scope);//编译nRow并添加到$scope中使得ng-click能被angularjs识别
                },
                "fnUpdateRow":function(a,b,c,d){
                    console.log(123);
                }
            }
        }])
    }
);